﻿using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;

namespace Yoozoo.Gameplay.Liberty.AI.Node
{
    [Category("Ggame/Liberty")]
    public class NpcIsTargetInsight : AIConditionBaseNode
    {
        public BBParameter<TargetType> targetType = TargetType.CurrentLockTarget;
        // 是否检测当前朝向
        public BBParameter<bool> checkDirection = false;
        // 是否检测射线，看是否有阻挡
        public BBParameter<bool> checkRaycast = false;
        // 是否使用targetDistance来快速判断距离（需要和NpcUpdateTargetDistance节点搭配使用）
        public BBParameter<bool> fast = false;

        protected override bool OnCheck()
        {
            AIEntity target = _entity.battleAgent.GetTarget(targetType.value);
            
            bool isInsight = false;
            if (target != null)
            {
                Vector3 targetPosition = target.battleAgent.transform.position;
                Vector3 attackerPosition = _entity.battleAgent.transform.position;

                float targetDistance = _entity.battleAgent.targetDistance;
                if (!fast.value)
                {
                    Vector3 targetVector = targetPosition - attackerPosition;
                    targetDistance = targetVector.magnitude;
                }
                // 视野检测
                isInsight = targetDistance <= _entity.propertyDataConfig.vision;

                // 检测朝向
                if (checkDirection.value)
                {
                    Vector3 targetVector = targetPosition - attackerPosition;
                    Vector3 targetDirection = targetVector.normalized;
                    if (Vector3.Dot(targetDirection, _entity.battleAgent.transform.forward) < 0)
                    {
                        isInsight = false;
                    }
                }
                
                // 射线检测是否被阻挡
                if (checkRaycast.value)
                {
                    Vector3 bodyPosition = attackerPosition + Vector3.up;
                    Vector3 targetBodyPosition = targetPosition + Vector3.up;
                    RaycastHit raycastHit;
                    bool hit = PhysicsUtils.RaycastNonAlloc(out raycastHit, bodyPosition, (targetBodyPosition-bodyPosition).normalized, targetDistance, BattleAgent.HandGunOnHitLayerMaskNames);
                    if (!hit || raycastHit.collider != target.onHitCollider)
                    {
                        isInsight = false;
                    }
                }
            }
            
            return isInsight;
        }
    }
}